package nl.hro.mobiqueen.ui;

import nl.hro.mobiqueen.R;
import nl.hro.mobiqueen.data.DatabaseAdapter;
import nl.hro.mobiqueen.data.objects.Event;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;
import nl.hro.mobiqueen.data.DatabaseSynchronizer;

public class Programma extends MobiBase {

	private static final int SCHEDULE_START_TIME = 9;

	private DatabaseAdapter databaseAdapter;

	Button artistOneButton;
	PopupWindow popupWindow;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.programma);

		// Synchronize database
		DatabaseSynchronizer synchronizer = new DatabaseSynchronizer(this);
		synchronizer.syncArtists();
		synchronizer.syncPodia();
		synchronizer.syncEvents();

		ScheduleView scheduleView = (ScheduleView) findViewById(R.id.scheduleView);

		databaseAdapter = new DatabaseAdapter(this).open();

		// Add the times:
		for (int i = SCHEDULE_START_TIME; i < 24; ++i) {
			String label = (i < 10 ? "0" + i : i) + ":00";
			scheduleView.addColumn(label);
		}

		/*
		 * Add the podia
		 */
		Cursor podiaCursor = databaseAdapter.listPodia();
		podiaCursor.moveToFirst();
		int nameColumn = podiaCursor.getColumnIndex(DatabaseAdapter.KEY_NAME);
		while (!podiaCursor.isAfterLast()) {
			scheduleView.addRow(podiaCursor.getString(nameColumn));
			podiaCursor.moveToNext();
		}

		/*
		 * Add the events
		 */
		Cursor eventCursor = databaseAdapter.listEvents();
		eventCursor.moveToFirst();
		while (!eventCursor.isAfterLast()) {
			Event event = DatabaseAdapter.getEventFromCursor(eventCursor);
			Cursor artist = databaseAdapter.findArtist(event.getArtist());

			int startHours = Integer
					.parseInt(event.getStartTime().split(":")[0]);
			int startMinutes = Integer
					.parseInt(event.getStartTime().split(":")[1]);
			int endHours = Integer.parseInt(event.getEndTime().split(":")[0]);
			int endMinutes = Integer.parseInt(event.getEndTime().split(":")[1]);

			int row = getCursorPositionById(podiaCursor, event.getPodium());
			int column = startHours - SCHEDULE_START_TIME;
			String label = artist.getString(artist
					.getColumnIndex(DatabaseAdapter.KEY_NAME));
			float position = startMinutes / 60.0f;
			float width = (endHours - startHours) + ((endMinutes - startMinutes) / 60.0f);

                        String genre = eventCursor.getString(eventCursor.getColumnIndex(DatabaseAdapter.KEY_GENRE));
                        
                        boolean isFavouriteGenre = true;
                        Cursor genreCursor = databaseAdapter.findFavoriteByName(genre);
                        if (genreCursor.getInt(genreCursor.getColumnIndex(DatabaseAdapter.KEY_FAVORITE))==0){
                            isFavouriteGenre = false;
                        }

                        boolean isFavouriteEvent = true;
                        Cursor artistCursor = databaseAdapter.findFavoriteById(event.getArtist());
                        if (artistCursor.getColumnIndex(DatabaseAdapter.KEY_FAVORITE) == -1 || artistCursor.getColumnIndex(DatabaseAdapter.KEY_FAVORITE) == 0){
                            isFavouriteEvent = false;
                        }

			scheduleView.setItem(row, column, label, event.getId(), position,
					width,genre,isFavouriteGenre,isFavouriteEvent);

			eventCursor.moveToNext();
		}

		scheduleView.addClickHandler(clickHandler);
	}

	private ScheduleView.IClickHandler clickHandler = new ScheduleView.IClickHandler() {

		public void handle(ScheduleViewItem item) {
			final int eventId = item.getId();

			LayoutInflater inflater = (LayoutInflater) Programma.this
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			View pview = inflater.inflate(R.layout.popup, null, false);
			popupWindow = new PopupWindow(pview, 150, 105, true);

			/*
			 * Fill popup info
			 */
			Cursor event = databaseAdapter.findEvent(eventId);
			TextView artistField = (TextView) pview.findViewById(R.id.artist);
			artistField.setText(item.getLabel());
			TextView genreField = (TextView) pview.findViewById(R.id.genre);
			genreField.setText(event.getString(event
					.getColumnIndex(DatabaseAdapter.KEY_GENRE)));

			// RelativeLayout01 is Main Activity Root Layout
			popupWindow.showAtLocation(findViewById(R.id.programmaLayout),
					Gravity.CENTER, 0, 0);

			Button navigeerNaarButton = (Button) pview
					.findViewById(R.id.popupButtonNavigeer);
			navigeerNaarButton.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					Intent intent = new Intent(v.getContext(),
							Plattegrond.class);

					popupWindow.dismiss();

					startActivity(intent);
				}
			});

			Button meerInfoButton = (Button) pview
					.findViewById(R.id.popupButtonMeerInfo);
			meerInfoButton.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					Intent intent = new Intent(v.getContext(),
							OptredenDetail.class);
					popupWindow.dismiss();
					intent.putExtra("eventId", eventId);
					startActivity(intent);
				}
			});
		}
	};

	private int getCursorPositionById(Cursor cursor, int id) {
		cursor.moveToFirst();
		int idColumn = cursor.getColumnIndex(DatabaseAdapter.KEY_ID);
		while (!cursor.isAfterLast()) {
			if (cursor.getInt(idColumn) == id) {
				return cursor.getPosition();
			}
			cursor.moveToNext();
		}
		return -1;
	}
}